package com.meta.framework.security.handle;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * java类简单作用描述
 *
 * @Title:
 * @Package: com.meta.framework.security.handle.
 * @Author: M.simple
 * @Remark: The modified content
 * @CreateDate: 2023-12-05 22:58
 * @Version: v2.0
 */
public class CustomLoginAuthenticationProvider extends DaoAuthenticationProvider {

	public CustomLoginAuthenticationProvider(UserDetailsService userDetailsService) {
		super();
		setUserDetailsService(userDetailsService);
	}

	protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			this.logger.debug("Authentication failed: no credentials provided");
			throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		} else {
			String presentedPassword = authentication.getCredentials().toString();
			if("CUSTOM_LOGIN_SMS".equals(presentedPassword)){
				//短信登录，不验证密码（还可以继续扩展，只要传进来的password标识即可）
			}else{
				BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
				if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
					this.logger.debug("Authentication failed: password does not match stored value");
					throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
				}
			}
		}
	}
}